{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f20eb6ec",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2 as cv \n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "188ff097",
   "metadata": {},
   "outputs": [],
   "source": [
    "filename = \"./grid.png\"\n",
    "green_hsv = {\"min\" : (35, 60, 60), \"max\" : (77, 255, 255)}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e031dd3",
   "metadata": {},
   "source": [
    "> `function`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d81e61b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def image_handle(img_original):\n",
    "    # * 图片处理，高斯滤波，转色域\n",
    "    img_hsv = cv.cvtColor(img_original, cv.COLOR_BGR2HSV)\n",
    "    # 通过hsv进行图像二值化\n",
    "    img_bin = cv.inRange(img_hsv, green_hsv[\"min\"], green_hsv[\"max\"])\n",
    "    cv.imshow(\"bin\", img_bin)\n",
    "    # 进行膨胀操作，得到mask\n",
    "    dilate_mask = cv.morphologyEx(img_bin, cv.MORPH_CLOSE, kernal_11_11, iterations=3)\n",
    "    dilate_mask = cv.morphologyEx(dilate_mask, cv.MORPH_DILATE, kernel=kernal_11_11, iterations=3)\n",
    "    img_mask = cv.bitwise_and(img_original, img_original, mask=dilate_mask)\n",
    "    \n",
    "    cv.imshow(\"mask_dilate\",  dilate_mask)\n",
    "    # 腐蚀得到单独的棋盘\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "6e702710",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "提取的文字（英文）：\n",
      " &A WBA 99+ 2H! 0 HAL 0 Hig o RP o\n",
      "\n",
      "GER RoR BRAD RSER BSE\n",
      "\n",
      "\n",
      "提取的文字（中文）：\n",
      " 综合   视频 99+   番剧 0   影视 0   直播 0   用户0\n",
      "\n",
      "综合排序   最多点击   最新发布   最多弹幕   最多收藏\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "-1"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pytesseract\n",
    "import cv2 as cv\n",
    "\n",
    "\n",
    "# 如果Tesseract不在系统PATH中，需要指定路径\n",
    "pytesseract.pytesseract.tesseract_cmd = r'C:\\\\Program Files\\\\Tesseract-OCR\\\\tesseract.exe'\n",
    "\n",
    "def extract_text_from_image(image_path, lang='eng'):\n",
    "    \"\"\"\n",
    "    从图片中提取文字\n",
    "    \n",
    "    参数:\n",
    "    - image_path: 图片路径\n",
    "    - lang: 语言代码（默认英文），中文用'chi_sim'\n",
    "    \"\"\"\n",
    "    # 打开图片\n",
    "    image = cv.imread(image_path)\n",
    "    # 使用Tesseract进行OCR\n",
    "    text = pytesseract.image_to_string(image, lang=lang)\n",
    "    return text\n",
    "\n",
    "# 示例：提取英文图片文字\n",
    "text = extract_text_from_image('image.png')\n",
    "print(\"提取的文字（英文）：\\n\", text)\n",
    "\n",
    "# 示例：提取中文图片文字\n",
    "text_chinese = extract_text_from_image('image.png', lang='chi_sim')\n",
    "print(\"\\n提取的文字（中文）：\\n\", text_chinese)\n",
    "img = cv.imread(\"grid.png\")\n",
    "\n",
    "cv.imshow(\"ret\", img)\n",
    "cv.waitKey(0)\n",
    "\n",
    "# zdl:: 这样就可以这却的完成图像, 好了别玩了\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "978a4e7a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "综 21 107 40 125 0\n",
      "['综', '21', '107', '40', '125', '0']\n",
      "x = 21, y = 107, w = 40, h = 125\n"
     ]
    },
    {
     "ename": "AttributeError",
     "evalue": "module 'PIL' has no attribute 'putText'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[36], line 23\u001b[0m\n\u001b[0;32m     21\u001b[0m     \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mx = \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mx\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m, y = \u001b[39m\u001b[38;5;132;01m{\u001b[39;00my\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m, w = \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mw\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m, h = \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mh\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m'\u001b[39m)\n\u001b[0;32m     22\u001b[0m     cv\u001b[38;5;241m.\u001b[39mrectangle(img, (x, hImg \u001b[38;5;241m-\u001b[39m y), (w, hImg \u001b[38;5;241m-\u001b[39m h), (\u001b[38;5;241m255\u001b[39m, \u001b[38;5;241m0\u001b[39m, \u001b[38;5;241m0\u001b[39m), \u001b[38;5;241m2\u001b[39m)\n\u001b[1;32m---> 23\u001b[0m     \u001b[43mpil\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mputText\u001b[49m(img, b[\u001b[38;5;241m0\u001b[39m], (x, hImg \u001b[38;5;241m-\u001b[39m y \u001b[38;5;241m+\u001b[39m \u001b[38;5;241m25\u001b[39m), cv\u001b[38;5;241m.\u001b[39mFONT_HERSHEY_COMPLEX,\n\u001b[0;32m     24\u001b[0m             \u001b[38;5;241m0.5\u001b[39m, (\u001b[38;5;241m50\u001b[39m, \u001b[38;5;241m50\u001b[39m, \u001b[38;5;241m255\u001b[39m), \u001b[38;5;241m1\u001b[39m)\n\u001b[0;32m     25\u001b[0m cv\u001b[38;5;241m.\u001b[39mimshow(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mresult\u001b[39m\u001b[38;5;124m\"\u001b[39m, img)\n\u001b[0;32m     26\u001b[0m cv\u001b[38;5;241m.\u001b[39mwaitKey(\u001b[38;5;241m0\u001b[39m)\n",
      "\u001b[1;31mAttributeError\u001b[0m: module 'PIL' has no attribute 'putText'"
     ]
    }
   ],
   "source": [
    "import pytesseract as ptestact\n",
    "import cv2 as cv \n",
    "from PIL import ImageDraw, ImageFont, Image\n",
    "ptestact.pytesseract.tesseract_cmd = (r'C:\\\\Program Files\\\\'\n",
    "    'Tesseract-OCR\\\\tesseract.exe')\n",
    "img = cv.imread(\"image.png\")\n",
    "img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n",
    "# eng chi_sim\n",
    "# print(ptestact.image_to_string(img, lang = \"chi_sim\"))\n",
    "boxes = ptestact.image_to_boxes(img, lang = \"chi_sim\")\n",
    "\n",
    "# detecting characters\n",
    "hImg, wImg, _ = img.shape\n",
    "img_pil = Image.fromarray(img)\n",
    "draw = ImageDraw.Draw(img_pil)\n",
    "for b in boxes.splitlines():\n",
    "    print(b)\n",
    "    b = b.split(' ')\n",
    "    print(b)\n",
    "    x, y, w, h = int(b[1]), int(b[2]), int(b[3]), int(b[4])\n",
    "    print(f'x = {x}, y = {y}, w = {w}, h = {h}')\n",
    "    cv.rectangle(img, (x, hImg - y), (w, hImg - h), (255, 0, 0), 2)\n",
    "    draw.text((x, hImg - y + 25), cv.FONT_HERSHEY_COMPLEX,\n",
    "            0.5, (50, 50, 255), 1)\n",
    "cv.imshow(\"result\", img)\n",
    "cv.waitKey(0)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "882757bb",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
